package com.k7k7.sserver.controlserver;

import com.k7k7.cserver.sceneclient.cmd.SceneServerCmd;
import com.k7k7.sserver.config.SceneServerConfig;
import com.k7k7.util.ElementUtil;
import com.k7k7.util.NetUtil;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;


/**
 * 接收总控服务器的线程
 *
 * @author Administrator
 */
public class ControlServerThread extends Thread {
	//singleton
	private static ControlServerThread instance;

	public static ControlServerThread getInstance() {
		return instance;
	}

	//
	private Socket ss;
	private BufferedReader reader;
	private PrintWriter writer;
	Logger log = Logger.getLogger(ControlServerThread.class);

	public ControlServerThread(String serverAddress, int serverPort) throws Exception {
		instance = this;
		ss = new Socket();
		InetSocketAddress iss = new InetSocketAddress(serverAddress, serverPort);
		try {
			ss.connect(iss);
			reader = new BufferedReader(new InputStreamReader(ss
					.getInputStream(), Charset.forName("UTF-8")));
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					ss.getOutputStream(), Charset.forName("UTF-8"))), true);
		} catch (Exception e) {
			if (reader != null) {
				reader.close();
			}
			if (writer != null) {
				writer.close();
			}
			ss.close();
			throw new Exception(("IOException"));
		}
		this.registerToControlServer();
	}

	private void registerToControlServer() {
		Element re = ElementUtil.getMsg();
		re.addAttribute("cmd", SceneServerCmd.register_server);
		Element url = DocumentHelper.createElement("url");
		url.add(DocumentHelper.createText(NetUtil.getAddress()));
		re.add(url);
		Element p = DocumentHelper.createElement("port");
		p.add(DocumentHelper.createText(SceneServerConfig.clientPort.toString()));
		re.add(p);
		this.sendMsg(re.asXML());
	}

	@Override
	public void run() {
		String input;
		while (ss != null) {
			try {
				input = reader.readLine().trim();
			} catch (IOException e) {
				continue;
			}
			if (null == input || input.equals("")) {
				continue;
			}
			handleMsg(input);
		}
	}

	private void handleMsg(String input) {

	}


	public void sendMsg(String msg) {
		if (this.writer != null) {
			this.writer.write(msg + "\0");
		}
	}
}
